package com.fs.system.sys_admin.controller;

import com.fs.system.college_admin.domain.College;
import com.fs.system.common.ResponseData;
import com.fs.system.student.domain.Student;
import com.fs.system.student.mapper.StudentMapper;
import com.fs.system.sys_admin.service.SysCollegeService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/sysAdminData")
public class SysDataController {

    @Resource
    private StudentMapper studentMapper;

    @Resource
    private SysCollegeService sysCollegeService;

    /**
     * 柱状图数据
     * @return 返回各学院学生人数及数据有效性标识
     */
    @GetMapping("/barDataStuCount")
    public ResponseData barDataStuCount() {
        Map<String, Object> resMap = new HashMap<>();
        List<Student> dbStudentList = studentMapper.getStudentInfo(null);

        // 过滤掉学生学院为null的学生
        List<Student> validDbStudentList = dbStudentList.stream()
                .filter(student -> student.getCollegeId() != null)
                .collect(Collectors.toList());

        // 封装横轴数据（学院）
        List<College> collegeList = sysCollegeService.selectAllCollegeList(null);
        Set<String> collegeNames = collegeList.stream()
                .map(College::getName)
                .collect(Collectors.toSet());

        List<Long> studentCountList = new ArrayList<>();
        boolean hasData = false;

        for (String collegeName : collegeNames) {
            long count = validDbStudentList.stream()
                    .filter(student -> student.getCollegeName().equals(collegeName))
                    .count();
            studentCountList.add(count);

            if (count > 0) {
                hasData = true;  // 只要有一个学院有学生数据，即认为有数据
            }
        }

        // 无数据时返回空集合，而非null
        resMap.put("collegeNames", collegeNames.isEmpty() ? Collections.emptyList() : new ArrayList<>(collegeNames));
        resMap.put("studentCountList", studentCountList.isEmpty() ? Collections.emptyList() : studentCountList);
        resMap.put("hasData", hasData); // 添加数据有效性标识

        return new ResponseData("200", "获取成功", resMap);
    }
}
